package adv9;

import java.net.*;
import java.io.*;

public class ChatThread extends Thread {
	private Socket s;

	public ChatThread(Socket s) {
		this.s = s;
	}

	@Override
	public void run() {
		System.out.println(s + "链接了，准备聊天");
		try {
			InputStream in = s.getInputStream();
			OutputStream out = s.getOutputStream();
			PrintWriter pw = new PrintWriter(out, true);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			while (true) {
				String client = br.readLine();
				if (client == null)
					break;
				System.out.println("客户端" + s.getInetAddress() + "说：" + client);
				pw.println(client + ",朕收到了！");
				pw.flush();
				if ("exit".equals(client)) {
					break;
				}
			}
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
			if (s != null)
				try {

					System.out.println("关闭"
							+ s.getInetAddress().getHostAddress());
					s.close();
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
		}
	}
}
